package com.canyou.controller;

import com.canyou.model.User;
import com.canyou.util.CryptUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.ActiveRecordException;

/**
 * 登录页
 * 
 * @created cgz 2012-12-15
 */
public class LoginController extends Controller {
	private static Logger logger = Logger.getLogger(LoginController.class);

	public void index() {
		render("/login.jsp");
	}

	/**
	 * 登录
	 * 
	 * @author cgz 2012-12-16
	 */
	@Before(LoginValidator.class)
	public void login() throws Exception {
		boolean flag = true;
		String msg = null;
		if (null == getSessionAttr("UserId")) {// 判断是否已登录
			String name = getPara("name");
			String pwd = CryptUtil.encrypt(getPara("password"));
			User user = new User();
			try {
				user = User.dao.findByNamePwd(name, pwd);
			} catch (ActiveRecordException e) {
				logger.fatal(e.getLocalizedMessage());
				flag = false;
				msg = "* 数据库异常！请稍候再试！";
			}
			if (null != user) {// 判断是否登录成功
				setSessionAttr("UserId", user.getStr("Id"));
				setSessionAttr("UserName", user.getStr("UserName"));
				setSessionAttr("RoleId", user.getStr("RoleId"));
			} else {
				flag = false;
				msg = "* 登陆失败！用户名或密码错误！";
			}
		}
		if (flag) {
			redirect("/default");
		} else {
			setAttr("login_error_msg", msg);
			index();
		}
	}

	/**
	 * 退出
	 * 
	 * @author cgz 2012-12-16
	 */
	public void loginout() {
		removeSessionAttr("UserId");
		removeSessionAttr("UserName");
		removeSessionAttr("RoleId");
		index();
	}
}
